<?php
if (isset($_GET['ajax'])) {
	define('AJAX','1');
}
require_once('global.php');

!$windid && Showmsg('not_login');
InitGP(array('action'));

$template = 'ajax_operate';

if (empty($_POST['step']) && !defined('AJAX')) {
	require_once(R_P.'require/header.php');
	$template = 'operate';
}

if ($action=='showping') {
	
	require_once(R_P.'require/msg.php');
	require_once(R_P.'require/forum.php');
	require_once(R_P.'require/credit.php');
	InitGP(array('selid','pid','page'));
	if (empty($selid) && empty($pid)) {
		Showmsg('selid_illegal');
	}
	empty($selid) && $selid = array($pid);
	$atcdb = array();
	$pids  = $ptpc = '';
	foreach ($selid as $key => $val) {
		if (is_numeric($val)) {
			$pids .= ($pids ? ',' : '').$val;
		} else {
			$ptpc = 1;
		}
	}
	$pw_tmsgs = GetTtable($tid);
	$atc = $db->get_one("SELECT t.fid,t.author,t.authorid,t.postdate,t.subject,t.anonymous,t.ptable,tm.ifmark FROM pw_threads t LEFT JOIN $pw_tmsgs tm ON tm.tid=t.tid WHERE t.tid='$tid'");
	$fid = $atc['fid'];
	$ptpc && $atcdb['tpc'] = $atc;
	$pw_posts = GetPtable($atc['ptable']);

	if ($pids) {
		$query = $db->query("SELECT pid,fid,author,authorid,postdate,subject,ifmark,anonymous,content FROM $pw_posts WHERE pid IN($pids) AND tid='$tid'");
		while ($rt = $db->fetch_array($query)) {
			$atcdb[$rt['pid']] = $rt;
		}
	}
	empty($atcdb) && Showmsg('data_error');

	$foruminfo = $db->get_one("SELECT name,f_type,style,password,allowvisit,allowhtm,cms,forumadmin,fupadmin FROM pw_forums WHERE fid='$fid' AND type<>'category'");
	!$foruminfo && Showmsg('data_error');
	wind_forumcheck($foruminfo);

	list($maxcredit,$minper,$maxper,$credittype,$markdt) = explode("|",$_G['markdb']);
	!$minper && $minper=0;
	!$maxper && $maxper=0;

	if ($winddb['groups']) {
		$gids = '';
		foreach (explode(',',$winddb['groups']) as $key=>$gid) {
			is_numeric($gid) && $gids .= ($gids ? ',' : '').$gid;
		}
		if ($gids) {
			require_once(R_P.'require/pw_func.php');
			$query = $db->query("SELECT mright FROM pw_usergroups WHERE gid IN($gids)");
			while (@extract($db->fetch_array($query))) {
				$p = P_unserialize($mright);
				if (is_array($p) && $p['markdb'] && $p['markable']) {
					$p['markable'] > $_G['markable'] && $_G['markable'] = $p['markable'];
					$s = explode('|',$p['markdb']);
					is_numeric($s[0]) && $s[0] > $maxcredit && $maxcredit = $s[0];
					is_numeric($s[1]) && $s[1] < $minper && $minper = $s[1];
					is_numeric($s[2]) && $s[2] > $maxper && $maxper = $s[2];
					$s[4]===0 && $markdt = 0;
				}
			}
		}
	}
	$admincheck = admincheck($foruminfo['forumadmin'],$foruminfo['fupadmin'],$windid);

	if ((!$admincheck && !$_G['markable']) || !$credittype || ($minper==0 && $maxper==0)) {
		Showmsg('no_markright');
	}
	$anonymous = 0;
	foreach ($atcdb as $key => $atc) {
		if ($db_pingtime && $timestamp-$atc['postdate']>$db_pingtime*3600 && $gp_gptype<>'system') {
			Showmsg('pingtime_over');
		}
		if ($winduid == $atc['authorid'] && !CkInArray($windid,$manager)) {
			Showmsg('masigle_manager');
		}
		if ($_POST['step'] == 1 && $_G['markable']<2 && !$admincheck && strpos($atc['ifmark'],'('.$windid.')')!==false) {
			Showmsg('no_markagain');
		}
		if ($_POST['step'] > 1 && strpos($atc['ifmark'],"(".$windid.")")===false) {
			Showmsg('have_not_showping');
		}
		$atc['anonymous'] && $anonymous++;
	}
	$cType		= GetCreditType();
	$credittype = explode(',',$credittype);
	$mcredit	= $db->get_one("SELECT credit FROM pw_memberinfo WHERE uid='$winduid'");
	$count		= count($atcdb);

	if (!$_POST['step']) {

		$creditselect = '';
		foreach ($credittype as $key=>$cid) {
			if (isset($cType[$cid])) {
				$creditselect .= '<option value="'.$cid.'">'.$cType[$cid].'</option>';
			}
		}
		if ($maxcredit) {
			$creditdb = explode("\t",$mcredit['credit']);
			if ($creditdb[0] >= $tdtime) {
				$leavepoint = abs($maxcredit-$creditdb[1]);
				$leavepoint == 0 && Showmsg('masigle_nopoint');
			} else {
				$leavepoint = $maxcredit;
			}
		}
		$reason_sel = '';
		$reason_a = explode("\n",$db_adminreason);
		foreach ($reason_a as $k=>$v) {
			if ($v = trim($v)) {
				$reason_sel .= "<option value=\"$v\">$v</option>";
			} else {
				$reason_sel .= "<option value=\"\">-------</option>";
			}
		}
		if ($anonymous==$count && $groupid!='3') {
			$check_Y = 'disabled';
			$check_N = 'checked';
		} else {
			$check_Y = 'checked';
			$check_N = '';
		}
		require_once PrintEot($template);footer();

	} elseif ($_POST['step']==1) {

		InitGP(array('cid','addpoint','ifmsg','atc_content'),'P');
		!in_array($cid,$credittype) && Showmsg('masigle_credit_right');

		$cUnit = GetCreditUnit();
		if (isset($cType[$cid])) {
			$name = $cType[$cid];
			$unit = $cUnit[$cid];
		} else {
			Showmsg('all_credit_error');
		}
		$addpoint = (int)$addpoint;
		$addpoint==0 && Showmsg('member_credit_error');
		$allpoint = $addpoint * $count;

		if ($addpoint>$maxper || $addpoint<$minper) {
			Showmsg('masigle_creditlimit');
		}
		if ($maxcredit) {
			$creditdb = explode("\t",$mcredit['credit']);
			if ($creditdb[0] < $tdtime) {
				$creditdb[0] = $tdtime;
				$creditdb[1] = abs($allpoint);
				if ($creditdb[1] > $maxcredit) {
					$leavepoint = max(0,$maxcredit-$creditdb[1]);
					Showmsg('masigle_point');
				}
			} else {
				if ($creditdb[1] + abs($allpoint) > $maxcredit) {
					$leavepoint = max(0,$maxcredit-$creditdb[1]);
					Showmsg('masigle_point');
				} else {
					$creditdb[0] = $timestamp;
					$creditdb[1]+= abs($allpoint);
				}
			}
			$newcreditdb = $creditdb[0]."\t".$creditdb[1];
			if ($mcredit) {
				$db->update("UPDATE pw_memberinfo SET credit='$newcreditdb' WHERE uid='$winduid'");
			} else {
				$db->update("INSERT INTO pw_memberinfo(uid,credit) VALUES('$winduid','$newcreditdb')");
			}
		}
		if ($markdt && $allpoint>0) {
			$credit = UserCredit($winduid,$cid);
			$credit < $allpoint && Showmsg('credit_enough');
			UserCredit($winduid,$cid,'set',-$allpoint);
		}
		$atc_content = Char_cv($atc_content);

		foreach ($atcdb as $pid => $atc) {
			UserCredit($atc['authorid'],$cid,'set',$addpoint);
			if ($db_autoban && $addpoint<0) {
				require_once(R_P.'require/autoban.php');
				autoban($atc['authorid']);
			}
			$newmark = $name.':'.($addpoint>0 ? '+' : '').$addpoint.'('.addslashes($windid).") ".substrs($atc_content,24);
			$ifmark	 = $atc['ifmark'] ? $newmark."\t".addslashes($atc['ifmark']) : $newmark;
			if (strlen($ifmark)>240) {
				$ifmark = substr($ifmark,0,240);
				$ifmark = substr($ifmark,0,strrpos($ifmark,"\t"));
			}
			if (!is_numeric($pid)) {
				$db->update("UPDATE pw_threads SET ifmark=ifmark+'$addpoint' WHERE tid='$tid'");
				$db->update("UPDATE $pw_tmsgs SET ifmark='$ifmark' WHERE tid='$tid'");
			} else {
				$db->update("UPDATE $pw_posts SET ifmark='$ifmark' WHERE pid='$pid'");
			}
			$atcdb[$pid]['ifmark'] = $ifmark;
			!$atc['subject'] && $atc['subject'] = substrs($atc['content'],35);

			if ($ifmsg && !$atc['anonymous']) {
				$msg = array(
					$atc['author'],
					$winduid,
					'ping_title',
					$timestamp,
					'ping_content',
					'',
					$windid,
					'fid'		=> $atc['fid'],
					'tid'		=> $tid,
					'subject'	=> $atc['subject'],
					'postdate'	=> get_date($atc['postdate']),
					'forum'		=> strip_tags($foruminfo['name']),
					'affect'    => "$name:$addpoint",
					'admindate'	=> get_date($timestamp),
					'reason'	=> $atc_content
				);
				writenewmsg($msg,1);
			}
			require_once(R_P.'require/writelog.php');
			$log = array(
				'type'      => 'credit',
				'username1' => $atc['author'],
				'username2' => $windid,
				'field1'    => $fid,
				'field2'    => '',
				'field3'    => '',
				'descrip'   => 'credit_descrip',
				'timestamp' => $timestamp,
				'ip'        => $onlineip,
				'tid'		=> $tid,
				'forum'		=> strip_tags($foruminfo['name']),
				'subject'	=> $atc['subject'],
				'affect'	=> "$name:$addpoint",
				'reason'	=> $atc_content
			);
			writelog($log);
		}
		if ($foruminfo['allowhtm'] && $page==1) {
			require_once(R_P.'require/template.php');
		}
		if (defined('AJAX')) {
			echo "success";
			foreach ($atcdb as $pid=>$atc) {
				echo "\t".$pid."\t";
				$ifmark = explode("\t",$atc['ifmark']);
				foreach ($ifmark as $key=>$value) {
					echo "<li>$value</li>";
				}
			}
			ajax_footer();
		} else {
			refreshto("read.php?tid=$tid&page=$page",'enter_thread');
		}
	} else {

		$groupid=='guest' && Showmsg('not_login');
		InitGP(array('ifmsg','atc_content'));
		$atc_content = Char_cv($atc_content);
		
		foreach ($atcdb as $pid => $atc) {
			$markdb = explode("\t",$atc['ifmark']);
			$cid = '';
			foreach ($markdb as $key=>$mark) {
				if (strpos($mark,"(".$windid.")")!==false) {
					$credit = substr($mark,0,strpos($mark,":"));
					list($addpoint) = explode("(",substr($mark,strpos($mark,":")+1));
					$addpoint = (int) $addpoint;
					unset($markdb[$key]);
					foreach ($cType as $k=>$v) {
						if ($v == $credit) {
							$cid = $k;break;
						}
					}
					break;
				}
			}
			!$cid && Showmsg('all_credit_error');
			$addpoint = $addpoint>0 ? -$addpoint : abs($addpoint);
			UserCredit($atc['authorid'],$cid,'set',$addpoint);

			$ifmark = implode("\t",$markdb);
			if (!is_numeric($pid)) {
				$db->update("UPDATE pw_threads SET ifmark=ifmark+'$addpoint' WHERE tid='$tid'");
				$db->update("UPDATE $pw_tmsgs SET ifmark='$ifmark' WHERE tid='$tid'");
			} else {
				$db->update("UPDATE $pw_posts SET ifmark='$ifmark' WHERE pid='$pid'");
			}
			$atcdb[$pid]['ifmark'] = $markdb;
			!$atc['subject'] && $atc['subject'] = substrs($atc['content'],35);

			if ($ifmsg) {
				$msg = array(
					$atc['author'],
					$winduid,
					'delping_title',
					$timestamp,
					'delping_content',
					'',
					$windid,
					'fid'		=> $atc['fid'],
					'tid'		=> $tid,
					'subject'	=> $atc['subject'],
					'postdate'	=> get_date($atc['postdate']),
					'forum'		=> strip_tags($foruminfo['name']),
					'affect'    => "$credit:$addpoint",
					'admindate'	=> get_date($timestamp),
					'reason'	=> $atc_content
				);
				writenewmsg($msg,1);
			}
			require_once(R_P.'require/writelog.php');
			$log = array(
				'type'      => 'credit',
				'username1' => $atc['author'],
				'username2' => $windid,
				'field1'    => $atc['fid'],
				'field2'    => '',
				'field3'    => '',
				'descrip'   => 'creditdel_descrip',
				'timestamp' => $timestamp,
				'ip'        => $onlineip,
				'tid'		=> $tid,
				'forum'		=> strip_tags($foruminfo['name']),
				'subject'	=> $atc['subject'],
				'affect'	=> "$name:$addpoint",
				'reason'	=> $atc_content
			);
			writelog($log);
		}

		if ($foruminfo['allowhtm'] && $page==1) {
			require_once(R_P.'require/template.php');
		}
		if (defined('AJAX')) {
			echo "success";
			foreach ($atcdb as $pid=>$atc) {
				echo "\t".$pid."\t";
				foreach ($atc['ifmark'] as $key=>$value) {
					echo "<li>$value</li>";
				}
			}
			ajax_footer();
		} else {
			refreshto("read.php?tid=$tid&page=$page",'enter_thread');
		}
	}

} elseif ($action=='recommend') {

	if (!$_POST['step']) {

		$atcinfo  = $db->get_one("SELECT subject,author,anonymous FROM pw_threads WHERE tid='$tid'");
		$atcinfo['anonymous'] && $atcinfo['author'] = $db_anonymousname;
		$atc_name = $atcinfo['subject'];
		require_once PrintEot($template);footer();

	} elseif ($_POST['step']==1) {

		($db_gdcheck & 16) && GdConfirm($_POST['gdcode']);
		InitGP(array('sendtoname'));
		InitGP(array('subject','atc_content'),'P',1);
		require_once(R_P.'require/msg.php');

		$userdb = '';
		if ($sendtoname) {
			$userdb = $db->get_one("SELECT username FROM pw_members WHERE username='$sendtoname'");
		}
		if (!$userdb) {
			$errorname = Char_cv($sendtoname);
			Showmsg('user_not_exists');
		}
		if (!$subject || !$atc_content) {
			Showmsg('tofriend_msgerror');
		}
		$msgdb = array(
			$userdb['username'],
			$winduid,
			$subject,
			$timestamp,
			$atc_content,
			'N',
			$windid
		);
		writenewmsg($msgdb,1);
		Showmsg('operate_success');

	} elseif ($_POST['step']==2) {

		($db_gdcheck & 16) && GdConfirm($_POST['gdcode']);
		InitGP(array('subject','atc_content','sendtoemail','sendtoname'));
	
		if (empty($subject)) {
			Showmsg('sendeamil_subject_limit');
		}
		if (empty($atc_content) || strlen($atc_content)<=20) {
			Showmsg('sendeamil_content_limit');
		} elseif (!ereg("^[-a-zA-Z0-9_\.]+\@([0-9A-Za-z][0-9A-Za-z-]+\.)+[A-Za-z]{2,5}$",$sendtoemail)) {
			Showmsg('illegal_email');
		}
		if ($timestamp-GetCookie('lastwrite')<=60) {//$gp_postpertime
			Showmsg('sendeamil_limit');
		}
		Cookie('lastwrite',$timestamp);
		require_once(R_P.'require/sendemail.php');
		$fromemail	= $winddb['email'];
		$fromname	= $windid;
		$sendinfo	= sendemail($sendtoemail,$subject,$atc_content,'email_additional');

		if ($sendinfo === true) {
			Showmsg('operate_success');
		} else {
			Showmsg(is_string($sendinfo) ? $sendinfo : 'mail_failed');
		}
	}

} elseif ($action=='report') {
	
	!$gp_allowreport && Showmsg('report_right');
	$pid = (int)GetGP('pid');
	$rt  = $db->get_one("SELECT tid FROM pw_report WHERE uid='$winduid' AND tid='$tid' AND pid='$pid'");
	$rt && Showmsg('have_report');

	if (empty($_POST['step'])) {

		require_once PrintEot($template);footer();

	} elseif ($_POST['step']==2) {

		InitGP(array('ifmsg','type','reason'),'P');

		$reason = Char_cv($reason);
		$db->update("INSERT INTO pw_report(tid,pid,uid,type,reason) VALUES ('$tid','$pid','$winduid','$type','$reason')");

		if ($ifmsg) {
			if ($pid>0) {
				$pw_posts = GetPtable('N',$tid);
				$sqlsel = "t.content as subject,t.postdate,";
				$sqltab = "$pw_posts t";
				$sqladd = "WHERE t.pid='$pid'";
			} else {
				$sqlsel = "t.subject,t.postdate,";
				$sqltab = "pw_threads t";
				$sqladd = "WHERE t.tid='$tid'";
			}
			$rs = $db->get_one("SELECT $sqlsel t.fid,f.forumadmin FROM $sqltab LEFT JOIN pw_forums f USING(fid) $sqladd");

			if ($rs['forumadmin']) {
				include_once(D_P.'data/bbscache/forum_cache.php');
				require_once(R_P.'require/msg.php');
				$admin_a = explode(',',$rs['forumadmin']);
				$msg = array(
					'',
					$winduid,
					'report_title',
					$timestamp,
					'report_content_'.$type,
					'',
					$windid,
					'fid'		=> $rs['fid'],
					'tid'		=> $tid.'#'.$pid,
					'postdate'	=> get_date($rs['postdate']),
					'forum'		=> $forum[$rs['fid']]['name'],
					'subject'	=> $rs['subject'],
					'admindate'	=> get_date($timestamp),
					'reason'	=> $reason
				);
				foreach ($admin_a as $key=>$forumadmin) {
					if(!$forumadmin) continue;
					$msg['0'] = $forumadmin;
					writenewmsg($msg,1);
				}
			}
		}
		Showmsg('report_success');
	}
}
?>